<?php

Class COL {

	private $data;

	function __construct() {
	}
	
	public function load_by_name ($name = '') {

		$name = urlencode($name);
		$url = COLURL . "&name=$name*";
		$data = file_get_contents($url);
		$this->data = unserialize($data);
		
	}
	
	public function load_by_id ($id = '') {

		$url = COLURL . "&response=full&id=$id";
		$data = file_get_contents($url);
		$this->data = unserialize($data);
	}

	public function getData() {
		return json_encode($this->data);
	}

	public function getDwcByIndex( $i=0 ) {
		
		$rec = $this->data['names'][$i];	
		$classifications = array( 'Kingdom', 'Phylum', 'Order', 'Family', 'Genus' );
		foreach( $rec['classification'] as $node ) {		
			if ( in_array( $node['rank'], $classifications ) ) {
				if ($node['rank'] == 'Order') $node['rank'] = 'Order_';
				$dwc[$node['rank']] = $node['name'];
			}
		}
		$dwc['SpecificEpithet'] = $rec['species'];
		if ($rec['rank'] == 'Infraspecies') {
			$dwc['InfraspecificRank'] = $rec['infraspecies_marker'];
			$dwc['InfraspecificEpithet'] = $rec['infraspecies'];
		}
		$dwc['ScientificName'] = $rec['name'];
		$dwc['AuthorYearOfScientificName'] = $rec['author'];
		$dwc['CatalogNumber'] = $rec['id'];
		$dwc['CatalogCode'] = 'COL';
		$dwc['BasisOfRecord'] = 'HumanObservation';

		return( $dwc );
	}
	
	public function getNames() {
		$data = $this->data;
		$names = $this->filterData($data['names']);
		return $names;
	}

	/**
	* Filters the search output of records without id ( 'common name' records )
	*/
	private function filterData($datum) {
		$names = array();
		if(count($datum)) {
			foreach ($datum as $data) {
				if(!is_null($data['id'])) {
					$names[] = $data;
				}
			}
		}
		return $names;
	}


	
}

?>
